package com.zhupf.stack;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author zhupf
 * @date 2024年02月20日 15:00
 * @Description
 *
 * 394. 字符串解码
 */
public class DecodeString {

    public static void main(String[] args) {
        DecodeString decodeString = new DecodeString();
        System.out.println(decodeString.decodeString("3[a2[c]]"));
    }

    private int idx;

    public String decodeString(String s) {
        StringBuffer sb = new StringBuffer();
        int len = s.length();
        Deque<String> deque = new LinkedList();
        idx = 0;
        while (idx< len){
            Character cur = s.charAt(idx);
            if(Character.isDigit(cur)){
                String num = this.getNum(s);
                deque.push(num);
            }else if('[' == cur || Character.isLetter(cur)){
                deque.push(String.valueOf(cur));
            }else {
                StringBuilder tmp = new StringBuilder();
                StringBuilder tmp2 = new StringBuilder();
                while (true){
                    String pop = deque.pop();
                    if("[".equals(pop)){
                        break;
                    }
                    tmp.insert(0, pop);
                }
                Integer num = Integer.valueOf(deque.pop());
                while (num>0){
                    tmp2.append(tmp);
                    num--;
                }
                deque.push(tmp2.toString());
            }
            idx++;
        }
        while (!deque.isEmpty()){
            sb.append(deque.removeLast());
        }
        return sb.toString();
    }

    public String getNum(String s){
        StringBuffer sb = new StringBuffer(String.valueOf(s.charAt(idx)));
        while (true){
            Character cur = s.charAt(idx+1);
            if(!Character.isDigit(cur)){
                break;
            }
            sb.append(cur);
            idx++;
        }
        return sb.toString();
    }
}
